package edu.bbu.commonproject.backend.server.services.thrift.communication;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;

import edu.bbu.commonproject.backend.utils.ServerLogger;

/**
 * The socket service class.
 */
public class SocketService
{
	public interface Iface
	{
		public abstract void handleSocketRequest(Socket socket);
	}
	
	private boolean started = false;
	
	/** The socket service interface handler. */
	private SocketService.Iface handle;
	
	/** The server socker. */
	private ServerSocket socketServer;
	
	/**
	 * The constructor.
	 * @param portNumber the port number.
	 * @param handle the handler.
	 * @throws IOException  throws exception if something went wrong.
	 */
	public SocketService(int portNumber, SocketService.Iface handle) throws IOException
	{
		this.handle = handle;
		socketServer = new ServerSocket(portNumber);
	}
	
	/**
	 * It start the server.
	 */
	public void server()
	{
		started = true;
		
		while (started)
		{
			try
			{
				final Socket socket = socketServer.accept();
				
				//TODO ThreadPoolServer here.
				new Thread(new Runnable()
				{
					public void run()
					{
						handle.handleSocketRequest(socket);
					}
					
				}).start();
				
			}
			catch (IOException e)
			{
				ServerLogger.log(Level.SEVERE, "I/O error ocurs when waiting for a connection.");
			}
		}
	}
	
	/**
	 * It stop the server.
	 * @throws IOException throw exeption if the server could not be stopped.
	 */
	public void stop() throws IOException
	{ 
		started = false;
		socketServer.close();
	}
}
